<template>
  <div class="change-tracking-container">
    <el-card class="tracking-card">
      <template #header>
        <div class="card-header">
          <h2>订单变更溯源</h2>
          <el-button type="primary">查询最近变更</el-button>
        </div>
      </template>
      
      <div class="tracking-content">
        <div class="filters">
          <el-form :model="filterForm" label-position="top" inline>
            <el-form-item label="订单号">
              <el-input v-model="filterForm.orderId" placeholder="输入订单号" clearable />
            </el-form-item>
            
            <el-form-item label="客户名称">
              <el-input v-model="filterForm.customerName" placeholder="输入客户名称" clearable />
            </el-form-item>
            
            <el-form-item label="变更类型">
              <el-select v-model="filterForm.changeType" placeholder="选择变更类型" clearable>
                <el-option label="数量变更" value="quantity" />
                <el-option label="交期变更" value="delivery" />
                <el-option label="规格变更" value="specification" />
                <el-option label="价格变更" value="price" />
                <el-option label="地址变更" value="address" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="变更时间">
              <el-date-picker
                v-model="filterForm.changeTimeRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
            
            <el-form-item label="操作人">
              <el-select v-model="filterForm.operator" placeholder="选择操作人" clearable>
                <el-option v-for="user in userOptions" :key="user.value" :label="user.label" :value="user.value" />
              </el-select>
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        
        <div class="tracking-table">
          <el-table :data="tableData" style="width: 100%" v-loading="loading" border stripe>
            <el-table-column type="expand">
              <template #default="props">
                <div class="change-details">
                  <el-descriptions title="详细变更内容" :column="3" border>
                    <template v-for="(item, key) in props.row.changeDetails" :key="key">
                      <el-descriptions-item :label="getFieldLabel(key)">
                        <div class="change-value">
                          <span class="old-value">{{ item.oldValue }}</span>
                          <el-icon><ArrowRight /></el-icon>
                          <span class="new-value">{{ item.newValue }}</span>
                        </div>
                      </el-descriptions-item>
                    </template>
                  </el-descriptions>
                  
                  <div class="change-comments" v-if="props.row.comments">
                    <h4>变更说明</h4>
                    <p>{{ props.row.comments }}</p>
                  </div>
                  
                  <div class="attachment-list" v-if="props.row.attachments && props.row.attachments.length">
                    <h4>相关附件</h4>
                    <el-space>
                      <el-button
                        v-for="(file, index) in props.row.attachments"
                        :key="index"
                        link
                        type="primary"
                        :icon="Document"
                        @click="viewAttachment(file)"
                      >
                        {{ file.name }}
                      </el-button>
                    </el-space>
                  </div>
                </div>
              </template>
            </el-table-column>
            
            <el-table-column prop="orderId" label="订单号" width="130" />
            <el-table-column prop="customerName" label="客户名称" width="120" />
            <el-table-column prop="changeType" label="变更类型" width="100">
              <template #default="scope">
                <el-tag :type="getChangeTypeTag(scope.row.changeType)">{{ getChangeTypeLabel(scope.row.changeType) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="changeTime" label="变更时间" width="160" sortable />
            <el-table-column prop="operator" label="操作人" width="100" />
            <el-table-column prop="reason" label="变更原因" />
            <el-table-column prop="status" label="审批状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusTag(scope.row.status)">{{ getStatusLabel(scope.row.status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="approver" label="审批人" width="100" />
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="scope">
                <el-button link type="primary" @click="viewDetail(scope.row)">查看详情</el-button>
                <el-button link type="primary" @click="exportChange(scope.row)">导出</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <div class="pagination">
            <el-pagination
              v-model:current-page="pagination.currentPage"
              v-model:page-size="pagination.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              background
              layout="total, sizes, prev, pager, next, jumper"
              :total="pagination.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
        
        <div class="visualization">
          <el-tabs v-model="activeTab" @tab-click="handleTabChange">
            <el-tab-pane label="变更统计" name="statistics">
              <div class="stat-charts">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-card class="stat-card">
                      <template #header>变更类型占比</template>
                      <div class="chart" ref="typeChart" style="height: 300px"></div>
                    </el-card>
                  </el-col>
                  
                  <el-col :span="8">
                    <el-card class="stat-card">
                      <template #header>变更趋势</template>
                      <div class="chart" ref="trendChart" style="height: 300px"></div>
                    </el-card>
                  </el-col>
                  
                  <el-col :span="8">
                    <el-card class="stat-card">
                      <template #header>客户变更频率排名</template>
                      <div class="chart" ref="customerChart" style="height: 300px"></div>
                    </el-card>
                  </el-col>
                </el-row>
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="变更追踪图" name="graph">
              <el-card>
                <div class="graph-container" ref="graphChart" style="height: 600px"></div>
              </el-card>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </el-card>
    
    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单变更详情"
      width="60%"
      :before-close="closeDetailDialog"
    >
      <div class="detail-content" v-if="currentOrder">
        <el-descriptions title="订单基本信息" :column="3" border>
          <el-descriptions-item label="订单号">{{ currentOrder.orderId }}</el-descriptions-item>
          <el-descriptions-item label="客户名称">{{ currentOrder.customerName }}</el-descriptions-item>
          <el-descriptions-item label="订单日期">{{ currentOrder.orderDate }}</el-descriptions-item>
          <el-descriptions-item label="原始交期">{{ currentOrder.originalDelivery }}</el-descriptions-item>
          <el-descriptions-item label="当前交期">{{ currentOrder.currentDelivery }}</el-descriptions-item>
          <el-descriptions-item label="变更次数">{{ currentOrder.changeCount }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="change-history">
          <h3>变更历史记录</h3>
          <el-timeline>
            <el-timeline-item
              v-for="(history, index) in currentOrder.changeHistory"
              :key="index"
              :timestamp="history.changeTime"
              :type="getChangeTypeIcon(history.changeType)"
              size="large"
              :hollow="index !== 0"
            >
              <el-card class="history-card">
                <h4>{{ getChangeTypeLabel(history.changeType) }}</h4>
                <p class="history-reason">变更原因：{{ history.reason }}</p>
                <div class="change-content">
                  <div v-for="(item, key) in history.changeDetails" :key="key" class="change-item">
                    <span class="field-label">{{ getFieldLabel(key) }}：</span>
                    <span class="old-value">{{ item.oldValue }}</span>
                    <el-icon><ArrowRight /></el-icon>
                    <span class="new-value">{{ item.newValue }}</span>
                  </div>
                </div>
                <div class="history-operator">
                  <span>操作人：{{ history.operator }}</span>
                  <span class="divider">|</span>
                  <span>审批人：{{ history.approver || '无需审批' }}</span>
                  <span class="divider">|</span>
                  <span>状态：
                    <el-tag size="small" :type="getStatusTag(history.status)">
                      {{ getStatusLabel(history.status) }}
                    </el-tag>
                  </span>
                </div>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="exportOrderChanges" type="primary">导出变更记录</el-button>
          <el-button @click="closeDetailDialog">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, watch } from 'vue'
import { ArrowRight, Document } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'

// 类型定义
interface ChangeDetail {
  oldValue: string | number;
  newValue: string | number;
}

interface ChangeDetails {
  [key: string]: ChangeDetail;
}

interface Attachment {
  id: string;
  name: string;
  url: string;
  type: string;
}

interface OrderChange {
  id: string;
  orderId: string;
  customerName: string;
  changeType: string;
  changeTime: string;
  operator: string;
  reason: string;
  status: string;
  approver: string;
  changeDetails: ChangeDetails;
  comments?: string;
  attachments?: Attachment[];
}

interface ChangeHistory extends OrderChange {
  changeDetails: ChangeDetails;
}

interface OrderDetail {
  orderId: string;
  customerName: string;
  orderDate: string;
  originalDelivery: string;
  currentDelivery: string;
  changeCount: number;
  changeHistory: ChangeHistory[];
}

interface Pagination {
  currentPage: number;
  pageSize: number;
  total: number;
}

// 表单数据
const filterForm = reactive({
  orderId: '',
  customerName: '',
  changeType: '',
  changeTimeRange: [] as Date[],
  operator: ''
})

// 表格数据
const tableData = ref<OrderChange[]>([])
const loading = ref(false)
const pagination = reactive<Pagination>({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 对话框相关
const detailDialogVisible = ref(false)
const currentOrder = ref<OrderDetail | null>(null)

// 图表相关
const activeTab = ref('statistics')
const typeChart = ref(null)
const trendChart = ref(null)
const customerChart = ref(null)
const graphChart = ref(null)

let typeChartInstance: echarts.ECharts | null = null
let trendChartInstance: echarts.ECharts | null = null
let customerChartInstance: echarts.ECharts | null = null
let graphChartInstance: echarts.ECharts | null = null

// 用户选项
const userOptions = [
  { label: '张经理', value: 'manager_zhang' },
  { label: '李销售', value: 'sales_li' },
  { label: '王客服', value: 'service_wang' },
  { label: '赵主管', value: 'supervisor_zhao' },
  { label: '钱财务', value: 'finance_qian' }
]

// 查询数据
const handleSearch = () => {
  loading.value = true
  
  // 模拟API请求
  setTimeout(() => {
    fetchMockData()
    loading.value = false
  }, 800)
}

// 重置表单
const resetForm = () => {
  // 使用类型断言解决索引签名问题
  const form = filterForm as { [key: string]: string | Date[] };
  Object.keys(form).forEach(key => {
    if (key === 'changeTimeRange') {
      form[key] = [] as Date[];
    } else {
      form[key] = '';
    }
  })
  
  handleSearch()
}

// 分页处理
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  handleSearch()
}

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val
  handleSearch()
}

// 获取变更类型标签样式
const getChangeTypeTag = (type: string): string => {
  const types: { [key: string]: string } = {
    quantity: 'info',
    delivery: 'warning',
    specification: 'danger',
    price: 'success',
    address: ''
  }
  return types[type] || 'info'
}

// 获取变更类型标签
const getChangeTypeLabel = (type: string): string => {
  const types: { [key: string]: string } = {
    quantity: '数量变更',
    delivery: '交期变更',
    specification: '规格变更',
    price: '价格变更',
    address: '地址变更'
  }
  return types[type] || type
}

// 获取字段标签
const getFieldLabel = (key: string): string => {
  const fields: { [key: string]: string } = {
    quantity: '数量',
    unitPrice: '单价',
    totalAmount: '总金额',
    deliveryDate: '交期',
    address: '收货地址',
    contact: '联系人',
    phone: '联系电话',
    specification: '规格',
    material: '材料',
    remark: '备注'
  }
  return fields[key] || key
}

// 获取状态标签样式
const getStatusTag = (status: string): string => {
  const statuses: { [key: string]: string } = {
    approved: 'success',
    pending: 'warning',
    rejected: 'danger',
    auto_approved: 'info'
  }
  return statuses[status] || ''
}

// 获取状态标签
const getStatusLabel = (status: string): string => {
  const statuses: { [key: string]: string } = {
    approved: '已批准',
    pending: '审批中',
    rejected: '已拒绝',
    auto_approved: '自动批准'
  }
  return statuses[status] || status
}

// 获取变更类型图标
const getChangeTypeIcon = (type: string): string => {
  const types: { [key: string]: string } = {
    quantity: 'primary',
    delivery: 'warning',
    specification: 'danger',
    price: 'success',
    address: 'info'
  }
  return types[type] || 'primary'
}

// 查看详情
const viewDetail = (row: OrderChange) => {
  loading.value = true
  
  // 模拟API请求获取详细信息
  setTimeout(() => {
    // 获取模拟的订单详情数据
    currentOrder.value = getMockOrderDetail(row.orderId)
    detailDialogVisible.value = true
    loading.value = false
  }, 500)
}

// 导出变更记录
const exportChange = (row: OrderChange) => {
  // 模拟导出功能
  console.log('导出变更记录:', row.id)
  
  // 实际实现应该调用后端API生成导出文件
  ElMessage({
    message: `正在导出订单 ${row.orderId} 的变更记录...`,
    type: 'success'
  })
}

// 导出订单所有变更记录
const exportOrderChanges = () => {
  if (!currentOrder.value) return
  
  // 模拟导出功能
  console.log('导出订单所有变更记录:', currentOrder.value.orderId)
  
  // 实际实现应该调用后端API生成导出文件
  ElMessage({
    message: `正在导出订单 ${currentOrder.value.orderId} 的完整变更历史...`,
    type: 'success'
  })
}

// 查看附件
const viewAttachment = (file: Attachment) => {
  // 实际应该打开文件预览或下载
  console.log('查看附件:', file)
  
  // 模拟打开新窗口查看
  window.open(file.url, '_blank')
}

// 关闭详情对话框
const closeDetailDialog = () => {
  detailDialogVisible.value = false
  currentOrder.value = null
}

// 处理标签页变化
const handleTabChange = () => {
  if (activeTab.value === 'statistics') {
    if (!typeChartInstance || !trendChartInstance || !customerChartInstance) {
      setTimeout(() => {
        initTypeChart()
        initTrendChart()
        initCustomerChart()
      }, 100)
    }
  } else if (activeTab.value === 'graph') {
    if (!graphChartInstance) {
      setTimeout(() => {
        initGraphChart()
      }, 100)
    }
  }
}

// 初始化变更类型占比图表
const initTypeChart = () => {
  if (!typeChart.value) return
  
  typeChartInstance = echarts.init(typeChart.value)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 10,
      data: ['数量变更', '交期变更', '规格变更', '价格变更', '地址变更']
    },
    series: [
      {
        name: '变更类型',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 35, name: '数量变更' },
          { value: 28, name: '交期变更' },
          { value: 15, name: '规格变更' },
          { value: 22, name: '价格变更' },
          { value: 10, name: '地址变更' }
        ]
      }
    ]
  }
  
  typeChartInstance.setOption(option)
}

// 初始化变更趋势图表
const initTrendChart = () => {
  if (!trendChart.value) return
  
  trendChartInstance = echarts.init(trendChart.value)
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['总变更数', '交期变更', '数量变更'],
      bottom: 10
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '总变更数',
        type: 'line',
        stack: 'Total',
        data: [25, 30, 20, 35, 40, 32],
        smooth: true,
        lineStyle: {
          width: 3
        },
        itemStyle: {
          color: '#409EFF'
        }
      },
      {
        name: '交期变更',
        type: 'line',
        stack: 'Total',
        data: [10, 12, 8, 15, 18, 14],
        smooth: true,
        lineStyle: {
          width: 3
        },
        itemStyle: {
          color: '#E6A23C'
        }
      },
      {
        name: '数量变更',
        type: 'line',
        stack: 'Total',
        data: [8, 10, 6, 12, 15, 10],
        smooth: true,
        lineStyle: {
          width: 3
        },
        itemStyle: {
          color: '#67C23A'
        }
      }
    ]
  }
  
  trendChartInstance.setOption(option)
}

// 初始化客户变更频率排名图表
const initCustomerChart = () => {
  if (!customerChart.value) return
  
  customerChartInstance = echarts.init(customerChart.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'value'
    },
    yAxis: {
      type: 'category',
      data: ['客户A', '客户B', '客户C', '客户D', '客户E'],
      inverse: true
    },
    series: [
      {
        name: '变更次数',
        type: 'bar',
        data: [28, 24, 18, 15, 12],
        label: {
          show: true,
          position: 'right'
        },
        itemStyle: {
          color: function(params: { dataIndex: number }) {
            const colorList = ['#F56C6C', '#F56C6C', '#E6A23C', '#67C23A', '#67C23A']
            return colorList[params.dataIndex]
          }
        }
      }
    ]
  }
  
  customerChartInstance.setOption(option)
}

// 初始化变更关系图
const initGraphChart = () => {
  if (!graphChart.value) return
  
  graphChartInstance = echarts.init(graphChart.value)
  
  const option = {
    title: {
      text: '订单变更关系图'
    },
    tooltip: {},
    legend: [
      {
        data: ['订单', '变更', '人员']
      }
    ],
    series: [
      {
        name: '变更关系',
        type: 'graph',
        layout: 'force',
        data: [
          {
            id: '1',
            name: 'ORD-2023001',
            symbolSize: 40,
            category: 0
          },
          {
            id: '2',
            name: '数量变更',
            symbolSize: 30,
            category: 1
          },
          {
            id: '3',
            name: '交期变更',
            symbolSize: 30,
            category: 1
          },
          {
            id: '4',
            name: '规格变更',
            symbolSize: 30,
            category: 1
          },
          {
            id: '5',
            name: '张经理',
            symbolSize: 25,
            category: 2
          },
          {
            id: '6',
            name: '李销售',
            symbolSize: 25,
            category: 2
          },
          {
            id: '7',
            name: 'ORD-2023002',
            symbolSize: 40,
            category: 0
          },
          {
            id: '8',
            name: '价格变更',
            symbolSize: 30,
            category: 1
          },
          {
            id: '9',
            name: '赵主管',
            symbolSize: 25,
            category: 2
          }
        ],
        links: [
          {
            source: '1',
            target: '2'
          },
          {
            source: '1',
            target: '3'
          },
          {
            source: '1',
            target: '4'
          },
          {
            source: '2',
            target: '5'
          },
          {
            source: '3',
            target: '6'
          },
          {
            source: '4',
            target: '5'
          },
          {
            source: '7',
            target: '8'
          },
          {
            source: '8',
            target: '9'
          }
        ],
        categories: [
          {
            name: '订单'
          },
          {
            name: '变更'
          },
          {
            name: '人员'
          }
        ],
        roam: true,
        label: {
          show: true,
          position: 'right'
        },
        force: {
          repulsion: 100,
          edgeLength: 80
        },
        lineStyle: {
          curveness: 0.3
        }
      }
    ]
  }
  
  graphChartInstance.setOption(option)
}

// 窗口大小变化时重绘图表
const resizeCharts = () => {
  typeChartInstance?.resize()
  trendChartInstance?.resize()
  customerChartInstance?.resize()
  graphChartInstance?.resize()
}

// 模拟获取数据
const fetchMockData = () => {
  // 模拟分页数据
  const mockData: OrderChange[] = [
    {
      id: '1',
      orderId: 'ORD-2023001',
      customerName: '客户A',
      changeType: 'quantity',
      changeTime: '2023-07-01 14:30:22',
      operator: '张经理',
      reason: '客户需求增加',
      status: 'approved',
      approver: '赵主管',
      changeDetails: {
        quantity: { oldValue: 100, newValue: 150 },
        totalAmount: { oldValue: 100000, newValue: 150000 }
      },
      comments: '客户临时追加订单，经与生产部门确认可以满足'
    },
    {
      id: '2',
      orderId: 'ORD-2023001',
      customerName: '客户A',
      changeType: 'delivery',
      changeTime: '2023-07-03 09:12:54',
      operator: '李销售',
      reason: '客户要求提前交货',
      status: 'rejected',
      approver: '赵主管',
      changeDetails: {
        deliveryDate: { oldValue: '2023-08-15', newValue: '2023-08-01' }
      },
      comments: '生产能力无法满足提前交货的需求'
    },
    {
      id: '3',
      orderId: 'ORD-2023002',
      customerName: '客户B',
      changeType: 'specification',
      changeTime: '2023-07-05 16:45:30',
      operator: '王客服',
      reason: '产品需求规格变更',
      status: 'approved',
      approver: '钱财务',
      changeDetails: {
        specification: { oldValue: '标准型号', newValue: '定制型号' },
        material: { oldValue: '铝合金', newValue: '不锈钢' }
      },
      attachments: [
        {
          id: 'att001',
          name: '规格变更说明书.pdf',
          url: '#',
          type: 'pdf'
        },
        {
          id: 'att002',
          name: '新规格图纸.dwg',
          url: '#',
          type: 'dwg'
        }
      ]
    },
    {
      id: '4',
      orderId: 'ORD-2023003',
      customerName: '客户C',
      changeType: 'price',
      changeTime: '2023-07-10 11:22:33',
      operator: '钱财务',
      reason: '原材料价格上涨',
      status: 'pending',
      approver: '',
      changeDetails: {
        unitPrice: { oldValue: 1000, newValue: 1100 },
        totalAmount: { oldValue: 200000, newValue: 220000 }
      }
    },
    {
      id: '5',
      orderId: 'ORD-2023004',
      customerName: '客户D',
      changeType: 'address',
      changeTime: '2023-07-12 10:20:30',
      operator: '李销售',
      reason: '客户收货地址变更',
      status: 'auto_approved',
      approver: '系统',
      changeDetails: {
        address: { oldValue: '上海市浦东新区张江高科技园区', newValue: '上海市闵行区莘庄工业区' },
        contact: { oldValue: '张三', newValue: '李四' },
        phone: { oldValue: '13800138000', newValue: '13900139000' }
      }
    }
  ]
  
  tableData.value = mockData
  pagination.total = 25 // 模拟总数据量
}

// 获取模拟订单详情
const getMockOrderDetail = (orderId: string): OrderDetail => {
  // 这里应该是API调用，现在用模拟数据
  return {
    orderId: orderId,
    customerName: orderId === 'ORD-2023001' ? '客户A' : '客户B',
    orderDate: '2023-06-15',
    originalDelivery: '2023-08-15',
    currentDelivery: '2023-08-20',
    changeCount: 3,
    changeHistory: [
      {
        id: '1',
        orderId: orderId,
        customerName: orderId === 'ORD-2023001' ? '客户A' : '客户B',
        changeType: 'quantity',
        changeTime: '2023-07-01 14:30:22',
        operator: '张经理',
        reason: '客户需求增加',
        status: 'approved',
        approver: '赵主管',
        changeDetails: {
          quantity: { oldValue: 100, newValue: 150 },
          totalAmount: { oldValue: 100000, newValue: 150000 }
        }
      },
      {
        id: '2',
        orderId: orderId,
        customerName: orderId === 'ORD-2023001' ? '客户A' : '客户B',
        changeType: 'delivery',
        changeTime: '2023-07-03 09:12:54',
        operator: '李销售',
        reason: '客户要求提前交货',
        status: 'rejected',
        approver: '赵主管',
        changeDetails: {
          deliveryDate: { oldValue: '2023-08-15', newValue: '2023-08-01' }
        }
      },
      {
        id: '3',
        orderId: orderId,
        customerName: orderId === 'ORD-2023001' ? '客户A' : '客户B',
        changeType: 'delivery',
        changeTime: '2023-07-08 10:45:12',
        operator: '李销售',
        reason: '生产延迟导致交期推迟',
        status: 'approved',
        approver: '赵主管',
        changeDetails: {
          deliveryDate: { oldValue: '2023-08-15', newValue: '2023-08-20' }
        }
      }
    ]
  }
}

// 组件挂载完成
onMounted(() => {
  // 初始加载数据
  handleSearch()
  
  // 监听窗口大小变化
  window.addEventListener('resize', resizeCharts)
  
  // 监听标签页变化，初始化图表
  watch(activeTab, handleTabChange)
})

// 组件卸载前清理
onUnmounted(() => {
  window.removeEventListener('resize', resizeCharts)
  typeChartInstance?.dispose()
  trendChartInstance?.dispose()
  customerChartInstance?.dispose()
  graphChartInstance?.dispose()
})
</script>

<style scoped>
.change-tracking-container {
  padding: 20px;
}

.tracking-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filters {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.change-details {
  padding: 20px;
  background-color: #f9fafc;
  border-radius: 4px;
}

.change-value {
  display: flex;
  align-items: center;
}

.old-value {
  text-decoration: line-through;
  color: #909399;
  margin-right: 10px;
}

.new-value {
  color: #67C23A;
  font-weight: bold;
  margin-left: 10px;
}

.change-comments {
  margin-top: 15px;
  padding: 10px;
  background-color: #fff;
  border-radius: 4px;
  border-left: 4px solid #E6A23C;
}

.attachment-list {
  margin-top: 15px;
}

.visualization {
  margin-top: 30px;
}

.stat-card {
  margin-bottom: 20px;
}

.graph-container {
  width: 100%;
  min-height: 600px;
}

.detail-content {
  padding: 10px;
}

.change-history {
  margin-top: 20px;
}

.history-card {
  margin-bottom: 10px;
}

.history-reason {
  color: #606266;
  margin: 10px 0;
}

.change-content {
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 10px;
}

.change-item {
  margin-bottom: 5px;
  display: flex;
  align-items: center;
}

.field-label {
  width: 100px;
  color: #606266;
}

.history-operator {
  font-size: 13px;
  color: #909399;
}

.divider {
  margin: 0 10px;
}
</style> 